package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.project.entity.Grade;
import com.project.entity.Role;
import com.project.mapper.GradeMapper;
import com.project.mapper.RoleMapper;
import com.project.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lovo
 * @since 2023-07-21
 */
@Service
public class RoleServiceImp extends ServiceImpl<RoleMapper, Role> implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Autowired
private GradeMapper gradeMapper;
    @Override
    public IPage<Role> selectRoles(Integer pageNO) {
        return roleMapper.selectPage(new Page<Role>(pageNO,3),null);
    }

    @Override
    public List<Grade> selectAllGrade() {
        return gradeMapper.selectAllGrade();
    }

    @Override
    public String addRole(String roleName, List<Integer> gradeList) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("r_name",roleName);
        Role testRole = roleMapper.selectOne(wrapper);
        if (testRole != null){
            return "该角色已存在";
        }
        else {
            Role newRole = new Role();
            newRole.setName(roleName);
            roleMapper.insert(newRole);
            roleMapper.insertRoleGrades(newRole.getRoleId(),gradeList);
            return "OK";
        }

    }

    @Override
    public void deleteRole(Integer roleId) {
        roleMapper.deleteGrades(roleId);
        roleMapper.deleteById(roleId);
    }

    @Override
    public Role selectRole(Integer roleId) {
        return roleMapper.selectRole(roleId);
    }

    @Override
    public void updateRole(Integer roleId, List<Integer> newGrades) {
        //先删除旧的权限
        roleMapper.deleteGrades(roleId);
        roleMapper.insertRoleGrades(roleId, newGrades);
    }
}
